<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { Search, Refresh, Download, RefreshRight } from "@element-plus/icons-vue"
import { type FormInstance } from "element-plus"
import { usePagination } from "@/hooks/usePagination"
import { moneyQuery, downLoadOrderTable } from "@/api/vouchercenter/index"
import { formatDateTime } from "@/utils/index"
import { getUserDataApi } from "@/api/user"
import { useUserStore } from "@/store/modules/user"
import { shortcuts } from "@/utils/dateSet"
defineOptions({
  name: "SearchRich"
})
const userStore = useUserStore()
const loading = ref<boolean>(false)
const loading1 = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  name: "",
  note: "",
  upName: "",
  searchDate: ""
})
// #region 所有账号名
const tableDataB = ref<any[]>([])
const getTableData = () => {
  loading.value = true
  getUserDataApi({
    page: 1,
    size: 100000,
    name: searchData.name || undefined,
    department: "",
    team: "",
    role: "",
    maxOrder: userStore.usermaxOrder
    // phone: searchData.phone || undefined
  })
    .then((res) => {
      tableDataB.value = res.data.userList
      console.log(tableDataB.value, "账号名")
      console.log(userStore.usernameID, "id")
    })
    .finally(() => {
      loading.value = false
    })
}
getTableData()
// #endregion

// #region  搜索功能
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    console.log(searchData.name, "遍历后的账号名")
    getmoneyQuery()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getmoneyQuery()
  }
  paginationData.currentPage = 1
}
// #endregion
// 查询数据
const tableData = ref<any>()
const tableTotal = ref<any>()
const getmoneyQuery = () => {
  getTableInfo()
}
const getTableInfo = async () => {
  loading.value = true
  if (!searchData.searchDate) {
    searchData.searchDate = []
  }
  await moneyQuery({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    // id: searchData.name || userStore.usernameID,
    id: searchData.name || "",
    note: searchData.note || "",
    upName: searchData.upName || "",
    start: new Date(searchData?.searchDate[0]).getTime() || "",
    end: new Date(searchData?.searchDate[1]).getTime() || ""
  })
    .then((res: any) => {
      tableTotal.value = res.data.total
      tableData.value = res.data.list
    })
    .finally(() => {
      loading.value = false
    })
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getmoneyQuery, { immediate: true })
/** 订单下载 默认下载所有数据，查询后下载所有符合查询条件的数据*/
const downLoad = async () => {
  loading1.value = true
  await downLoadOrderTable({
    id: searchData.name || "",
    note: searchData.note || "",
    upName: searchData.upName || "",
    start: new Date(searchData?.searchDate[0]).getTime() || "",
    end: new Date(searchData?.searchDate[1]).getTime() || ""
  })
    .then((res: any) => {
      const blob = new Blob([res.data], {
        type: "application/xlsx;charset=utf-8"
      })
      // console.log(res)
      const downloadElement = document.createElement("a")
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = "查询记录.xlsx"
      document.body.appendChild(downloadElement)
      downloadElement.click()
      window.URL.revokeObjectURL(href)
    })

    .finally(() => {
      loading1.value = false
    })
}
const handleRefresh = () => {
  getmoneyQuery()
}

const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]
</script>

<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="searchDate" label="日期">
          <el-date-picker
            v-model="searchData.searchDate"
            type="datetimerange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-select v-model="searchData.name" filterable clearable style="width: 240px">
            <el-option v-for="item in tableDataB" :key="item.name" :label="item.name" :value="item.id"
          /></el-select>
        </el-form-item>
        <el-form-item label="充值手机号" prop="note">
          <el-input v-model.trim="searchData.note" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="上级名称" prop="upName">
          <el-input v-model.trim="searchData.upName" placeholder="请输入上级名称" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 表格内容 -->
    <el-card v-loading="loading">
      <div class="toolbar-wrapper">
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle @click="downLoad" />
          </el-tooltip>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-center">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="交易日期" width="180" align="center">
            <template #default="scope"> {{ formatDateTime(scope.row.date) }} </template>
          </el-table-column>
          <el-table-column prop="overview" label="交易概述" width="180" align="center" />
          <el-table-column prop="upName" label="上级名称" align="center" />
          <el-table-column prop="note" label="充值手机号" align="center" />
          <el-table-column prop="remark" label="充值内容" align="center" />
          <el-table-column prop="orderReference" label="订单编号" align="center" />
          <el-table-column prop="image" label="图片" align="center">
            <template #default="scope">
              <img v-if="scope.row.image !== null" :src="scope.row.image" alt="" width="80" height="80" />
            </template>
          </el-table-column>
          <el-table-column label="用户名" align="center">
            <template #default="scope"> {{ scope.row.userEntity?.name }} </template>
          </el-table-column>
          <el-table-column label="交易金额(元)" align="center">
            <template #default="scope">
              <div :class="scope.row.amount > -1 ? 'active' : 'active1'">
                {{ scope.row.amount }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="balance" label="账户余额(元)" align="center" />
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="tableTotal"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <div class="loading" v-loading="loading1" v-if="loading1">下载中...</div>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.active {
  color: red;
}
.active1 {
  color: green;
}
.table-center {
  margin-bottom: 20px;
}
.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
:deep(.el-loading-parent--relative) {
  z-index: 199999 !important;
}
.loading {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
</style>
